package com.peng.leetcode.list;

import java.util.*;

/**
 * ReverseKGroup
 * <p>
 * 25. K 个一组翻转链表
 *
 * @author: lupeng6
 * @create: 2021/3/2 11:10
 */
public class ReverseKGroup {

    public static void main(String[] args) {
        ListNode listNode = BuildListNode.tailInsert(1, 2, 3, 4, 5);
        ListNode node = new ReverseKGroup().reverseKGroup(listNode, 2);
        PrintListNode.print(node);
    }


    public ListNode reverseKGroup(ListNode head, int k) {
        Deque<ListNode> stack = new LinkedList<>();
        ListNode dummy = new ListNode(0);
        ListNode curr = dummy;

        while (true) {
            int count = 0;
            ListNode temp = head;
            while (temp != null && count < k) {
                stack.push(temp);
                temp = temp.next;
                count++;
            }
            if (count < k) {
                curr.next = head;
                break;
            }
            while (!stack.isEmpty()) {
                ListNode node = stack.poll();
                curr.next = node;
                curr = curr.next;
            }
            curr.next = temp;
            head = temp;
        }
        return dummy.next;
    }


}
